﻿namespace Business
open System
open System.Linq.Expressions
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
[<AutoOpen>]
module Utils =
  type Result<'TSuccess,'TFailure> = 
      | Success of 'TSuccess
      | Failture of 'TFailure
  let bind switchFunction = 
     function 
     |Success s -> switchFunction s
     |Failture f -> Failture f
  let (|>>) twoTrackInput switchFunction =
     bind switchFunction twoTrackInput
  let (>=>) switch1 switch2 x =
     match switch1 x with 
     |Success s -> switch2 s
     |Failture f -> Failture f
  let tryCatch f x =
     try 
        f x |> Success
     with 
     | ex -> Failture ex.Message
  let switch f x = 
    f x |> Success
  let map oneTrackFunction twoTrackInput = 
    match twoTrackInput with
    | Success s -> Success (oneTrackFunction s)
    | Failture f -> Failture f
  let success x = Success x
  let fail x = Failture x
  let doUnit f x =
    f x |> ignore
    x
  let toLinq (expr : Expr<'a -> 'b>) =   
     let lambda = ((expr.ToLinqExpression()) :?> MethodCallExpression).Arguments.[0] :?> LambdaExpression
     //let call = linq :?> MethodCallExpression
     //let lambda = call.Arguments.[0] :?> LambdaExpression
     Expression.Lambda<Func<'a, 'b>>(lambda.Body, lambda.Parameters) 
     
  let url (uri:string) = try 
                          let ub = System.UriBuilder(uri)
                          let uriString = System.Text.StringBuilder(ub.Scheme).Append("://").Append(ub.Host.Replace("www.","")).Append(":").Append(ub.Port).Append(ub.Path).Append(ub.Query).ToString()
                          let URI = System.Uri(uriString)
                          Some(URI, uri.IndexOf("://www.") > -1)
                         with
                         //| :? System.UriFormatException -> None
                         | _ -> None
     